package com.becca.cake.service.users.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.becca.cake.core.exception.ServiceException;
import com.becca.cake.core.qiniu.FileNameRuleHelp;
import com.becca.cake.core.qiniu.QiNiuGoodsPicTemplate;
import com.becca.cake.core.qiniu.bean.QiNiuResponse;
import com.becca.cake.dao.users.UserManagerDAO;
import com.becca.cake.model.system.AdminDO;
import com.becca.cake.model.users.UserCouponModel;
import com.becca.cake.model.users.UserFollowHolidayModel;
import com.becca.cake.model.users.UsersModel;
import com.becca.cake.service.users.IUserManagerService;
import com.becca.cake.util.DateUtils;
import com.becca.cake.util.JsonUtil;
import com.becca.cake.util.MD5Util;

/**
 * 用户管理-用户查询service实现类
 * @copyright  尊星(上海)信息科技有限公司
 * @author yellow
 * @date 2016年5月16日 下午11:33:36
 */
@Service
public class UserManagerServiceImpl implements IUserManagerService {

    @Autowired
    private UserManagerDAO userManagerDAO;

    @Override
    @Cacheable(key = "'selectAllUsers'", value = "monmondecake")
    public List<UsersModel> selectAllUsers(Map<String, Object> map) throws Exception {
        return this.userManagerDAO.selectAllUsers(map);
    }

    @Override
    public Long selectAllUsersCount(Map<String, Object> map) throws Exception {

        return this.userManagerDAO.selectAllUsersCount(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void insertOrUpdateUser(UsersModel usersModel) throws Exception {
        if (usersModel.getId() == null) {
            this.userManagerDAO.insertUser(usersModel);
        } else {
            this.userManagerDAO.updateUser(usersModel);
        }
    }

    @Override
    public void deleteUserById(String id) throws Exception {
        this.userManagerDAO.deleteUserById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public void addOrUpdateUser(UsersModel usersModel, MultipartFile files, String fileTempPath,
                                AdminDO adminDo) throws Exception {
        //step1:数据校验
        UsersModel.validateAddOrUpdateParam(usersModel, files);
        //step2:上传图片
        String userPicPath = "";
        if (!files.isEmpty()) {
            //step3:重新生成图片文件名
            String fileName = FileNameRuleHelp.getGoodsPictureFileName() + "."
                              + FilenameUtils.getExtension(files.getOriginalFilename());
            String filePath = fileTempPath + File.separator + fileName;
            File localFile = new File(filePath);
            files.transferTo(localFile);
            //step4:调用七牛上传图片
            QiNiuResponse response = QiNiuGoodsPicTemplate.uploadFile(localFile, fileName);
            if (response.isSuccess()) {
                userPicPath = QiNiuGoodsPicTemplate.getDownloadUrl(response.key);
            } else {
                throw new ServiceException(UsersModel.PICTURE_UPLAOD_FAIL);
            }
            //step5:删除本地图片
            localFile.delete();
        }
        //step6:添加或修改用户
        if (StringUtils.isNotEmpty(userPicPath)) {
            usersModel.setHeadPic(userPicPath);
        }
        if (usersModel.getId() == null) {//添加
            // 用户密码加密
            usersModel.setPassword(MD5Util.getMD5Password(UsersModel.USER_DEFAULT_PASSWORD));
            usersModel.setStatus(UsersModel.USER_STATUS_USABLE);
            usersModel.setCreatedName(adminDo.getTrueName());
            this.userManagerDAO.insertUser(usersModel);
        } else {//修改
            usersModel.setUpdatedName(adminDo.getTrueName());
            this.userManagerDAO.updateUser(usersModel);
        }
    }

    @Override
    public String valideMobileIsExist(String mobileNo) throws Exception {
        UserCouponModel.validMobileNoNull(mobileNo);
        String flag = this.userManagerDAO.valideMobileIsExist(mobileNo);
        if (flag == "1") {
            return JsonUtil.returnJsonUnSuccess(UsersModel.MOBILE_ALREADY_REGIST);
        } else {
            return JsonUtil.returnJsonUnSuccess(UsersModel.MOBILE_COULD_USER);
        }

    }

    @Override
    public List<UserCouponModel> selectUserCouponsByMobileNo(Map<String, Object> map)
                                                                                     throws ServiceException {
        String mobileNo = String.valueOf(map.get("mobileNo"));
        UserCouponModel.validMobileNoNull(mobileNo);
        return this.userManagerDAO.selectUserCouponsByMobileNo(map);
    }

    @Override
    public Long selectUserCouponsByMobileNoCount(Map<String, Object> map) throws ServiceException {
        return this.userManagerDAO.selectUserCouponsByMobileNoCount(map);
    }

    @Override
    public List<UserFollowHolidayModel> selectFollowHolidays(Map<String, Object> map)
                                                                                     throws ServiceException {
        return this.userManagerDAO.selectFollowHolidays(map);
    }

    @Override
    public Long selectFollowHolidaysCount(Map<String, Object> map) throws ServiceException {
        return this.userManagerDAO.selectFollowHolidaysCount(map);
    }

    @Override
    public UsersModel selectUserById(Integer userId) throws ServiceException {
        if(userId == null){
            throw new ServiceException(UsersModel.USER_ID_NULL);
        }
        return this.userManagerDAO.selectUserById(userId);
    }

    @Override
    public void updUserStatusById(String userId,String status,String userName) throws ServiceException {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", userId);
        paramMap.put("status", status);
        paramMap.put("userName", userName);
        Long isUserStatusExist = this.userManagerDAO.isUserStatusExist(paramMap);
        if (isUserStatusExist != 0) {
            if ("0".endsWith(status)) {
                throw new ServiceException(UsersModel.FIXING_STATUS_EXIST);
            } else {
                throw new ServiceException(UsersModel.FIXING_NOT_STATUS_EXIST);
            }
        }
        this.userManagerDAO.updUserStatusById(paramMap);
    }

    @Override
    public UsersModel selectUserByMobileNo(String mobileNo) throws ServiceException {
        UsersModel userModel = this.userManagerDAO.selectUserByMobileNo(mobileNo);
        UsersModel.validMobileNo(userModel);
        return userModel;
    }

    @Override
    public List<UsersModel> selectUserChart(String days,String userChartStartDate,String userChartEndDate) throws ServiceException {
        Date nowDate = DateUtils.getSomeDayDate(0);
        Date startDate = null;
        if("1".equals(days)){
             startDate = DateUtils.getSomeDayDate(-30);
        }else if("2".equals(days)){
             startDate = DateUtils.getSomeDayDate(-90);
        }else if("3".equals(days)){
             startDate = DateUtils.getSomeDayDate(-180);
        }
       
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("nowDate", nowDate);
        map.put("startDate", startDate);
        map.put("userChartStartDate", userChartStartDate);
        map.put("userChartEndDate", userChartEndDate);
        return this.userManagerDAO.selectUserChart(map);
    }
}
